import React, { memo, useEffect, useRef } from "react"
import { IndicatorWrapper } from "./style"

const Indicator = memo((props) => {
  const { selectIndex = 0 } = props
  const currentRef = useRef()

  useEffect(() => {
    // 1. 获取 当前 item 相关的数据
    const selectItemEl = currentRef.current.children[selectIndex]
    const itemOffsetLeft = selectItemEl.offsetLeft
    const itemWidth = selectItemEl.clientWidth

    // 2. 获取 指示器 content 的宽度
    const contentWidth = currentRef.current.clientWidth
    // 获取整个可移动区的宽度，即包含 溢出部分
    const contentScroll = currentRef.current.scrollWidth

    // 获取右边最多可移动的距离
    const totalDistance = contentScroll - contentWidth
    // 3. 获取 指示器 要滚动的距离
    let distance = itemOffsetLeft + itemWidth * 0.5 - contentWidth * 0.5
    if (distance < 0) distance = 0
    if (distance > totalDistance) distance = totalDistance
    currentRef.current.style.transform = `translate(${-distance}px)`
  }, [selectIndex])
  return (
    <IndicatorWrapper>
      <div className="i-content" ref={currentRef}>
        {props.children}
      </div>
    </IndicatorWrapper>
  )
})



export default Indicator
